// pages/login/login.js
import {userLogin, reqUserInfo} from "../../api/user"
import {setStorage} from "../../utils/storage"
import loginBehavior from './behavior'
import { toast} from '../../utils/extendApi'
Page({

  behaviors: [loginBehavior],

  // methods: {
    toLogin() {
      wx.login({
        success: async ({code}) => {
          if (code) {
            console.log(code);
            const {data: token} = await userLogin(code)
            // 设置返回的token
            setStorage('token',token)
            this.setToken(token)
            this.getUserInfo()
          }else {
            toast({title: '登录失败，请重新尝试',icon: 'error'})
          }
        },
        error: async (msg) => {
          console.log(msg)
        }
      })
    },
  
    async getUserInfo() {
      const res = await reqUserInfo()
      res.data.defaultshippingaddress = JSON.parse(res.data.defaultshippingaddress)
      res.data.defaultstore = JSON.parse(res.data.defaultstore)
      // 设置默认地址
      this.changeAddressObj(res.data.defaultshippingaddress)
      // 设置默认商铺
      this.changeStoreObj(res.data.defaultstore)
      setStorage('userInfo',res.data)
      this.setUserInfo(res.data)
      // 返回上一级页面
      wx.navigateBack()
    }
  // }
})